﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;
using DeepTime.DL.DataModels;

namespace DeepTime.DataSources.DL
{
    /// <summary>
    /// Provides access to the uploaded image meta data persistance
    /// </summary>
    public class UploadedImageMetaDataDataSource : IDataSource<UploadedImageMetaDataDataModel>
    {
        #region Class Members

        private AzureTableServiceContext<UploadedImageMetaDataDataModel> _ServiceContext = null;

        #endregion Class Members

        #region Constructors

        public UploadedImageMetaDataDataSource()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            _ServiceContext = new AzureTableServiceContext<UploadedImageMetaDataDataModel>(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials, "UploadedImageMetaDataTable");

            //
            // This should be optimized at a later stage since you don't need to check the table exists EVERY time an instance of the data source is created.
            //
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist(_ServiceContext.TableName);
        }

        #endregion Constructors

        #region Methods

        public IEnumerable<UploadedImageMetaDataDataModel> Select()
        {
            var results = from c in _ServiceContext.Table
                          select c;

            var query = results.AsTableServiceQuery<UploadedImageMetaDataDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }

        public void Delete(UploadedImageMetaDataDataModel itemToDelete)
        {
            if (!_ServiceContext.Entities.Contains(_ServiceContext.GetEntityDescriptor(itemToDelete)))
            {
                _ServiceContext.AttachTo(_ServiceContext.TableName, itemToDelete, "*");
            }

            _ServiceContext.DeleteObject(itemToDelete);
            _ServiceContext.SaveChanges();
        }

        public void Insert(UploadedImageMetaDataDataModel newItem)
        {
            _ServiceContext.AddObject(_ServiceContext.TableName, newItem);
            _ServiceContext.SaveChanges();
        }

        public void Update(UploadedImageMetaDataDataModel itemToUpdate)
        {
            if (!_ServiceContext.Entities.Contains(_ServiceContext.GetEntityDescriptor(itemToUpdate)))
            {
                _ServiceContext.AttachTo(_ServiceContext.TableName, itemToUpdate, "*");
            }
            else
            {
                _ServiceContext.UpdateObject(itemToUpdate);
            }
            _ServiceContext.SaveChanges();
        }

        #endregion Methods
    }
}
